package com.hzsai.mininotecaller.common;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * hzsai 2020/1/16
 * usage:
 **/
@Component
public class I18nPool implements ApplicationContextAware {

    private static ApplicationContext context = null;

    public static String getWord(String word) {
        Locale locale = LocaleContextHolder.getLocale();
        return context.getBean(MessageSource.class).getMessage(word, null, locale);
    }

//    @Autowired
//    private MessageSource messageSource;

//    public String getWord(String word) {
//
//        Locale locale = LocaleContextHolder.getLocale();
//
//        return messageSource.getMessage(word, null, locale);
//    }

    /**
     * Set the ApplicationContext that this object runs in.
     * Normally this call will be used to initialize the object.
     * <p>Invoked after population of normal bean properties but before an init callback such
     * as {@link InitializingBean#afterPropertiesSet()}
     * or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},
     * {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
     * {@link MessageSourceAware}, if applicable.
     *
     * @param applicationContext the ApplicationContext object to be used by this object
     * @throws ApplicationContextException in case of context initialization errors
     * @throws BeansException              if thrown by application context methods
     * @see BeanInitializationException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
}
